<template>
  <div class="detail" v-if="service_detail"> 
    <e-cellbox class="top">
      <e-cell-item  class="top-picture" >
        <el-carousel  v-if="service_detail.imgList && service_detail.imgList.length" trigger="click" height="375px" > 
          <el-carousel-item v-for="item in service_detail.imgList" :key="item.goodsImgUrl">
              <div class="img" :style="{backgroundImage: 'url(' + item.goodsImgUrl + ')'}"   ></div>  
          </el-carousel-item>
        </el-carousel>
      </e-cell-item>
      <e-cell-item class="top-info">
        <div class="top-info-header" >
          <h4>{{service_detail.goodsName}}</h4>
          <state-tip 
            :class="{'negative': service_detail.status == 1}" 
            v-if="service_detail.checkStatus == 1 " >
              {{service_detail.status == 1 ? '已结束':'进行中'}}
          </state-tip>  
        </div>
        <p class="small weak">{{service_detail.remarks }}</p> 
        <div  class="price"  v-if="selectedItems.length === groups">
          {{price | formatMoney}}
          <span class="market-price">{{mPrice | formatMoney}}</span>
        </div>
        <div  class="price"  v-if="selectedItems.length < groups">
          {{minPrice | formatMoney}}
          <span v-if='maxPrice > minPrice' >
            - {{maxPrice | noPreformatMoney}}
          </span>
        </div>

        <e-cellbox class="selectItems table-row-height" style="display:table-row" v-for="(items,indexs) in service_detail.attributeMappingListUse" :key="indexs">
          <e-cell-item class="select-title">{{items.attrName+"："}}</e-cell-item>
          <e-cell-item>
            <el-radio-group class="checker-plain" :value="items.selectedItem" @input="handleChange(items, indexs, $event)">
              <el-radio 
                v-for="(item,index)  in items.selects"
                :label="item.attrCode"
                :key="index"
                :disabled="forbiddenSelectItems.indexOf(item.attrCode) !== -1">
                  {{item.attrName}}
              </el-radio>
            </el-radio-group>
          </e-cell-item>
        </e-cellbox>
        <e-cellbox class="num table-row-height"  style="display:table-row"  v-if="(service_detail.checkStatus === 1) && (service_detail.status != 1)" > 
          <e-cell-item class="select-title" >数量：</e-cell-item>
          <e-cell-item>
            <el-input-number controls="true" class="input-number-primary"  size="small"  v-model="currentNum"  :min="0" :max="matchedStock.buyTimesLimit == 0 ? matchedStock.stock : matchedStock.buyTimesLimit"></el-input-number> 
            <span class="weak small" v-if="selectedItems.length === groups">{{matchedStock.buyTimesLimit == 0 ? `(库存${matchedStock.stock || 0}件)` : `(库存${matchedStock.stock}件, 限购${matchedStock.buyTimesLimit}件)`}}</span>
            <span class="weak small" v-if="selectedItems.length < groups">{{`(库存${totalStock}件)`}}</span>
          </e-cell-item>
        </e-cellbox>
        <div class="tips actived-tips"  v-if="(service_detail.checkStatus === 1) && (service_detail.status != 1) && selectedItems.length < groups"  >  
          请选择【
          <span  class="select-tips" v-for="(items,index) in service_detail.attributeMappingListUse"  :key="index">
            <span  v-if="!(items.selectedItem)">{{items.attrName}}</span>
          </span> 
          】
        </div> 
        <div class="tips actived-tips"  v-if="(service_detail.checkStatus === 1) && (service_detail.status != 1) && selectedItems.length === groups"  >  
          你已经选择了【
          <span  class="select-tips" v-for="(items,index) in service_detail.attributeMappingListUse"  :key="index">
            <span v-for="(item,$index)  in items.selects" v-if="items.selectedItem == item.attrCode"  :key="$index">{{item.attrName}}</span>
          </span> 
          】
        </div> 

        <ol class="tips" v-if="service_detail.status == 2 ">
          <h4>草稿中</h4>
        </ol>

        <ol class="tips" v-if="!((service_detail.checkStatus == 1) && (service_detail.status != 1)) && (service_detail.status != 2) ">
          <h4 >{{goodsStateList[service_detail.checkStatus].title}}</h4>
          <li class="weak"  v-if="service_detail.checkStatus == 2" >{{service_detail.checkOpinion}}</li>
          <li class="weak"  v-if="service_detail.checkStatus != 2"
            v-for='item in goodsStateList[service_detail.checkStatus].tips'  
            :key='item.text'
          >
            {{item.text}}
          </li>
        </ol>

      </e-cell-item>
    </e-cellbox>
    <div class="main">
      <el-tabs v-model="activeName">
        <el-tab-pane label="详情" name="first">
          <div class="lab">
            <el-row class='detail-table'>
              <el-col class='detail-table-item' :span="8" v-if="service_detail.brandName">
                <span>品牌：</span>
                <span>{{service_detail.brandName}}</span>
              </el-col>
              <el-col class='detail-table-item' :span="8" v-for="(item,index) in service_detail.baseFieldList"  :key="index"  v-if="item.valueTexts[0]" >
                <span>{{item.nameText+"："}}</span>
                <span v-if="item.valueType == 3">{{item.valueTexts[0]+'  --  '+item.valueTexts[1]}}</span>
                <span v-else-if="item.valueType == 4">
                  <span v-for="(addr,index) in item.valueTexts" :key="index">{{addr}}</span>
                </span>
                <span v-else-if="item.valueType == 5 || item.valueType == 7 || item.valueType == 11">
                  <span v-for="(addr,index) in item.valueTexts" :key="index">
                    {{addr}}
                    <span>{{(index + 1) < (item.valueTexts.length) ? '，' : ''}}</span>
                  </span>
                </span>
                <span v-else-if="item.valueType == 9">
                  {{`${item.valueTexts[0]}-${item.valueTexts[1]}`}}
                </span>
                <!-- <span v-else-if="item.valueType == 10">
                  {{valueType10(item.valueTexts[0])}}
                </span> -->
                <span v-else>{{item.valueTexts[0]}}</span>
              </el-col>
            </el-row>
          </div>
          <div class="rich-text" v-html="service_detail.descPc" ></div>
        </el-tab-pane>
        <el-tab-pane label="相关信息" name="second">
          <e-cellbox class="info-list " v-for="(item,index) in service_detail.otherFieldList"   v-if="item.valueTexts[0]" :key="index">
            <span >{{item.nameText+"："}}</span>
            <span v-if="item.valueType == 3">{{item.valueTexts[0]+'  --  '+item.valueTexts[1]}}</span>
            <span v-else-if="item.valueType == 4">
              <span v-for="(addr,index) in item.valueTexts" :key="index">{{addr}}</span>
            </span>
            <span v-else-if="item.valueType == 5 || item.valueType == 7 || item.valueType == 11">
              <span v-for="(addr,index) in item.valueTexts" :key="index">
                {{addr}}
                <span>{{(index + 1) < (item.valueTexts.length) ? '，' : ''}}</span>
              </span>
            </span>
            <span v-else-if="item.valueType == 9">
              {{`${item.valueTexts[0]}-${item.valueTexts[1]}`}}
            </span>
            <!-- <span v-else-if="item.valueType == 10">
              {{valueType10(item.valueTexts[0])}}
            </span> -->
            <span v-else>{{item.valueTexts[0]}}</span> 
          </e-cellbox>
        </el-tab-pane>
      </el-tabs>
    </div> 
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import StateTip from './components/StateTip'
export default {
  components: {
    StateTip
  },
  computed: {
    ...mapGetters({
      service_detail: 'service_detail'
    })
  },
  mounted () {
    let goodsCode = ''
    let rdmkey = ''
    let url = ''
    if (this.$route.params.serviceId === 'preview') { // 不需要登录的
      rdmkey = this.GetQueryString('rdmkey')
      url = '/preview/goods'
    } else { // 需要登录的
      goodsCode = this.$route.params.serviceId
      url = '/goods/getGoods'
    }
    this.$store.dispatch('service_detail', {goodsCode, rdmkey, url}).then(() => {
      this.groups = this.service_detail.attributeMappingListUse.length
      let priceList = [] // 价格都是分，过滤器里面有把分转为元
      for (let i = 0; i < this.service_detail.goodsSkuList.length; i++) {
        this.totalStock += this.service_detail.goodsSkuList[i].stock
        priceList.push(this.service_detail.goodsSkuList[i].salePrice)
      }
      this.maxPrice = Math.max.apply(Math, priceList)
      this.minPrice = Math.min.apply(Math, priceList)
      console.log('this.minPrice', this.minPrice)
      console.log('this.maxPrice', this.maxPrice)
      // 计算并改变详情下面属性‘表格’的行高
      setTimeout(() => {
        let tableRow = document.getElementsByClassName('detail-table-item')
        let tableRowRes = []
        let tableRowGroup = []
        for (let i = 0; i < tableRow.length; i++) {
          tableRowRes.push(tableRow[i].offsetHeight)
        }
        for (let j = 0; j < Math.ceil(tableRowRes.length / 3); j++) {
          let endIndex = tableRowRes.length > (3 * (j + 1)) ? 3 * (j + 1) : tableRowRes.length
          tableRowGroup.push(tableRowRes.slice(3 * j, endIndex))
          for (let m = 3 * j; m < endIndex; m++) {
            tableRow[m].style.height = Math.max.apply(Math, tableRowGroup[j]) + 'px'
          }
        }
      }, 20)
    })
  },
  data () {
    return {
      activeName: 'first',
      radioValueList: [], // 选中的value
      matchedStock: [], // 库存匹配结果
      currentNum: 1, // 选择商品的数量
      goodsStateList: [
        {
          title: '商品审核中',
          tips: [
            {text: '1、请耐心等待审核结果'},
            {text: '2、可以继续发布其他商品或服务'}
          ]
        },
        {
          title: '商品已结束',
          tips: [
            {text: '1、请联系卖家咨询'},
            {text: '2、逛逛商家的其他商品或服务'}
          ]
        },
        {
          title: '商品审核不通过'
        }
      ],
      price: 0,
      mPrice: 0, // 市场价
      selectedItemInfo: [], // 用于控制有切换当前行，还是其他行
      selectedItems: [], // 已选中的项，无重复
      allSelectItems: [], // 所有的选项的集合[a,b,c,d,attrCode,attrCode...]
      goodsSkuGroup: [], // 所有选项组合的集合[[a1,b3],[a4,b3],...]
      forbiddenSelectItems: [], // 禁选项列表
      totalStock: 0,
      groups: 1,
      maxPrice: 0,
      minPrice: 0
    }
  },
  methods: {
    GetQueryString (name) {
      let after = window.location.hash.split('?')[1]
      if (after) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
        let r = after.match(reg)
        if (r != null) {
          return decodeURIComponent(r[2])
        } else {
          return null
        }
      }
    },
    handleChange (items, indexs, $event) {
      let item = items.selects.filter((item) => {
        return $event === item.attrCode
      })[0]
      if (this.service_detail.attributeMappingListUse[indexs].selectedItem === item.attrCode) { // 点击选中项
        this.$set(this.service_detail.attributeMappingListUse[indexs], 'selectedAttrName', '') // 同一个分组不再有选中项
        this.$set(this.service_detail.attributeMappingListUse[indexs], 'selectedItem', '')
        for (let j = 0; j < this.selectedItemInfo.length; j++) {
          if (this.selectedItemInfo[j].attrCode === item.attrCode) {
            this.selectedItemInfo.splice(j, 1)
            this.selectedItems.splice(j, 1)
            break
          }
        }
      } else { // 点击未选中的项 1、同一分组，2、不同分组 -- 点击未选中的项-----同一分组
        if (this.service_detail.attributeMappingListUse[indexs].selectedAttrName === item.parentAttrCode) { // 同一分组有选中项
          this.$set(this.service_detail.attributeMappingListUse[indexs], 'selectedItem', item.attrCode)
          for (let j = 0; j < this.selectedItemInfo.length; j++) {
            if (this.selectedItemInfo[j].parentAttrCode === item.parentAttrCode) {
              this.selectedItemInfo.splice(j, 1)
              this.selectedItems.splice(j, 1)
              break
            }
          }
          this.selectedItemInfo.push({attrCode: item.attrCode, parentAttrCode: item.parentAttrCode, parentAttrName: item.parentAttrName})
          this.selectedItems.push(item.attrCode)
        } else { // 同一分组 没有选中项--点击未选中的项-----不同分组
          this.$set(this.service_detail.attributeMappingListUse[indexs], 'selectedAttrName', item.parentAttrCode)
          this.$set(this.service_detail.attributeMappingListUse[indexs], 'selectedItem', item.attrCode)
          this.selectedItemInfo.push({attrCode: item.attrCode, parentAttrCode: item.parentAttrCode, parentAttrName: item.parentAttrName})
          this.selectedItems.push(item.attrCode)
        }
      }
      this.someItemChangeForbidden()

      // 匹配找相应的对的上的价格、数量、限购数
      // 现在只能选上匹配上的 && 库存不为0,否则就是还没有选完每一组
      this.currentNum = 1
      if (this.service_detail) {
        for (let i = 0; i < this.service_detail.attributeMappingListUse.length; i++) {
          this.radioValueList[i] = this.service_detail.attributeMappingListUse[i].selectedItem
        }
        let radioValue = this.radioValueList.sort()
        for (let j = 0; j < this.service_detail.goodsSkuList.length; j++) {
          let minValue = this.service_detail.goodsSkuList[j].attrCodeList.sort()
          if (radioValue.join('') === minValue.join('')) {
            this.matchedStock = this.service_detail.goodsSkuList[j]
            this.price = this.service_detail.goodsSkuList[j].salePrice
            this.mPrice = this.service_detail.goodsSkuList[j].price
            this.currentNum = (this.matchedStock.stock < 1) ? 0 : 1
            return
          }
        }
      }
    },
    someItemChangeForbidden () {
      // 找出每一行被其他行的已选的 - 禁选的项，求和 就是所有禁选项
      /*
        所有库存不为0的组合 -- this.goodsSkuGroup
        当前行元素集合  -- currentLineSelectItems
        当前的所有选中项 -- this.selectedItems
        去除当前行后，所有选中项 -- noCurrentLineSelectedItems（ = 当前所有选中项 - 当前行元素）
        去除当前行后，所有可能的选项 -- nowGoodsSkuGroup
        去除当前行后，当前所有可能的选项 - currentLineSelectItemsFind
        当前行被其他行禁的选项 -- this.forbiddenSelectItems
        //step
        1、遍历根据所有选项数组，即每一行，
        2、根据所有选项数组，当前行元素数组 -- 找出当前行元素集合  -- currentLineSelectItems
        3、遍历当前行元素，找出在当前选中集合中的，并删除 -- 得出去除当前行元素后的所有选中项-- noCurrentLineSelectedItems
        4、遍历所有库存不为0的组合，根据noCurrentLineSelectedItems，找出满足没有当前行的选项集合 -- 去除当前行后，所有可能的选项 -- nowGoodsSkuGroup
        5、当前行元素集合，到去除当前行后，所有可能的选项中，找当前行元素  -- 去除当前行后，当前行所有可能的选项 - currentLineSelectItemsFind
        6、当前行元素集合，减去当前行的可选项 --  当前行被其他行禁的选项 -- this.forbiddenSelectItems
        7、循环每一行都找出当前行被其他行禁选的 -- 得到所有禁选项
      */
      this.goodsSkuGroup = []
      for (let i = 0; i < this.service_detail.goodsSkuList.length; i++) {
        if (this.service_detail.goodsSkuList[i].stock > 0) { // 出去库存为0的项
          this.goodsSkuGroup.push(this.service_detail.goodsSkuList[i].attrCodeList)
        }
      }

      this.forbiddenSelectItems = [] // 重新设置禁选项
      for (let i = 0; i < this.service_detail.attributeMappingListUse.length; i++) {
        let noCurrentLineSelectedItems = [].concat(this.selectedItems)
        let currentLineSelectItems = []
        for (let j = 0; j < this.service_detail.attributeMappingListUse[i].selects.length; j++) {
          currentLineSelectItems.push(this.service_detail.attributeMappingListUse[i].selects[j].attrCode)
        }
        for (let j = 0; j < noCurrentLineSelectedItems.length; j++) {
          if (currentLineSelectItems.indexOf(noCurrentLineSelectedItems[j]) > -1) {
            noCurrentLineSelectedItems.splice(j, 1)
          }
        }

        // 匹配出所有可选组合
        let nowGoodsSkuGroup = []
        for (let j = 0; j < this.goodsSkuGroup.length; j++) {
          let notMarchFlag = false
          for (let k = 0; k < noCurrentLineSelectedItems.length; k++) {
            if (this.goodsSkuGroup[j].indexOf(noCurrentLineSelectedItems[k]) === -1) {
              notMarchFlag = true
              break
            }
          }
          if (!notMarchFlag) {
            nowGoodsSkuGroup.push(this.goodsSkuGroup[j])
          }
        }

        // 找出是当前行的元素设为可选，（或没找到的设为禁选）
        let currentLineSelectItemsFind = []
        for (let j = 0; j < currentLineSelectItems.length; j++) {
          for (let k = 0; k < nowGoodsSkuGroup.length; k++) {
            if (nowGoodsSkuGroup[k].indexOf(currentLineSelectItems[j]) > -1) {
              currentLineSelectItemsFind.push(currentLineSelectItems[j])
            }
          }
        }
        currentLineSelectItemsFind = this.uniqueArrItem(currentLineSelectItemsFind)

        for (let j = 0; j < currentLineSelectItems.length; j++) {
          if (currentLineSelectItemsFind.indexOf(currentLineSelectItems[j]) === -1) {
            this.forbiddenSelectItems.push(currentLineSelectItems[j])
          }
        }
      }
    },
    uniqueArrItem (arr) {
      let res = []
      let json = {}
      for (let i = 0; i < arr.length; i++) {
        if (!json[arr[i]]) {
          res.push(arr[i])
          json[arr[i]] = 1
        }
      }
      return res
    }
  }
}
</script>

<style lang="scss" scoped>


.detail-table{
  .el-col-8{
    padding: 5px 10px;
    text-align: justify;
    >span:nth-of-type(1){
      font-weight:800;
    }
  }
}
.detail{
  word-break:break-all;
}
.table-row-height{
  height: 50px;
  &.num{
    height: 61px;
  }
}
.img{
  height: 100%;
  background-repeat: no-repeat;
  background-position:center center;
  background-size:cover;
  }
.top{
  padding: 30px;
  .top-picture{
    width: 500px;
    .el-carousel{
      overflow: hidden;
    }
  }
  .top-info{
    padding-left: 40px;
    .select-title{
      width: 50px;
      // line-height: 50px;
      line-height: 40px;
      white-space: nowrap;
      padding-right: 10px;
    }
    .top-info-header{
      line-height: 24px;
      margin-bottom:5px;
      h4{
        font-size: 24px;
        font-weight: normal;
        display: inline;
      }
    }
    p{
      line-height: 16px;
    }
    .price{
      line-height: 76px;
      font-size: 30px;
      color: #fc6f00;
      .market-price{
        text-decoration: line-through;
        font-size: 16px;
        color: $color-sub;
        font-weight: normal;
        padding-right: 5px;
        box-sizing: border-box;
      }
    }
    .selectItems{
      margin-bottom: 10px;
    }
    .num{
      padding:3px 0 34px;
      .cell-item{
        vertical-align: middle;
        &.select-title{
          line-height: 30px;
        }
      }
      
    }
    .tips{
      min-height: 58px;
      margin-top: 5px;
      width: 500px;
      background: #f5f5f5;
      text-align: justify;
      
      padding:14px 20px 8px;
      box-sizing:border-box;
      &.actived-tips{
        margin-top: 40px;
        padding:18px 20px;
      }
      .select-tips{
        span{
          margin: 0 6px;
        }
      }
      h4{
        font-size: 18px;
        font-weight: 600px;
        line-height: 30px;
      }
      li{
        line-height: 24px;
        margin: 4px 0;
      }
    }
    .actived-tips{
      color: #fc6f00;
    }
  }
}
.main{
  min-height: 100%;
  border-top:20px solid $color-background;
  background: #fff;
  .el-tab-pane{
    margin: 28px 60px;
    .lab{
      line-height: 30px;
      margin-bottom: 34px;
    }
  }
  .info-list{
    line-height: 26px;
    margin-bottom:17px;
    >span:nth-of-type(1){
      font-weight:800;
    }
  }
}
.frame .detail {
    padding: 0;
}
</style>
<style  lang="scss" >
  .detail{
    .rich-text{
      p{
        line-height: 36px;
        padding: 10px 0;
        text-indent:2em;
        img{
          display: block;
          margin:0 auto;
          margin-bottom:30px;
        }
      }
    }
    .checker-plain.el-radio-group {
      margin: 0;
    }
    .el-tabs__header{
      .el-tabs__nav{
        height:60px;
        line-height:60px;
        margin-left:60px;
        div{
          min-width:100px;
          text-align:center;
        }
      }
    }
  }
</style>
